<?php

/**
 * Mediad co,ltd
 *
 * @category   Mediad2
 * @package    Mediad2_Model
 * @copyright  Copyright (c) 2012-2013 Mediad co,ltd. (http://www.Mediad.cn)
 * @license    New BSD License
 * @version    $Id: Abstract.php 1 2012-02-02 11:19:00Z tany@Mediad.cn $
 */

/**
 * @category   Mediad2
 * @package    Mediad2_Model
 */
abstract class Mediad2_Model_Abstract
{	
	
	/**
	 *
	 * @param array $options
	 */
	public function __construct(array $options = null)
	{
		if (is_array($options)) {
			$this->setOptions($options);
		}
	}
	
	/**
	 *
	 * @param string $name
	 * @param string $value
	 * @throws Exception
	 */
	public function __set($name, $value)
	{
		$method = 'set' . $name;
		if (('mapper' == $name) || !method_exists($this, $method)) {
			throw new Exception('Invalid model property');
		}
		$this->$method($value);
	}
	
	/**
	 *
	 * @param string $name
	 * @throws Exception
	 */
	public function __get($name)
	{
		$method = 'get' . $name;
		if (('mapper' == $name) || !method_exists($this, $method)) {
			throw new Exception('Invalid model property');
		}
		return $this->$method();
	}
	
	/**
	 *
	 * @param array $options
	 */
	public function setOptions(array $options)
	{
		$methods = get_class_methods($this);
		foreach ($options as $key=>$value)
		{
			$method = 'set' . ucfirst($key);
			if (in_array($method, $methods)) {
				$this->$method($value);
			}
		}
		return $this;
	}
	
	/**
	 * @return a Array
	 */
	public function toArray()
	{
		$vars = get_class_vars(get_class($this));
		$results = array();
		foreach ($vars as $key=>$value)
		{
			$method = 'get' . ucfirst($key);
			$varValue = $this->$method();
			$results[$key] = $varValue;
		}
		return $results;
	}
	
	/**
	 * return a xml sring
	 */
	public function toXmlString()
	{
		$className = get_class($this);
		$xml = '<' . $className . '>';
		$vars = get_class_vars($className);
		foreach ($vars as $key=>$value)
		{
			$xml .= '<' . $key . '>';
			$method = 'get' . ucfirst($key);
			$varValue = $this->$method();
			$xml .= $varValue;
			$xml .= '</' . $key . '>';
		}
		$xml .= '</' . $className . '>';
		return $xml;
	}
	
	/**
	 * @return a JSON
	 */
	public function toJson()
	{
		$result = Zend_Json::encode($this->toArray());
		return $result;
	}
	
	/**
	 * @param json object
	 */
	public function fromJson($json)
	{
		$options = Zend_Json::decode($json);
		if (is_array($options)) {
			$this->setOptions($options);
		}
	}
	
	/**
	 * get class vars
	 * 
	 * @return array of vars
	 */
	public function getVars()
	{
		return array_keys(get_class_vars(get_class($this))); // $this
	}
	
	/**
	 * get class methods
	 * 
	 * @return array of method name
	 */
	public function getMethods()
	{
		return get_class_methods(get_class($this));
	}
}